package com.atguigu.tingshu.search.consumer;

import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听专辑上下架消息的消费者
 *
 * @author Haoran Sun
 * @since 2024/08/20
 */

@Component
@Slf4j
public class AlbumSearchConsumer {

    @Resource
    private ItemService itemService;

    /**
     * 接收专辑上架消息
     */
    @RabbitListener(queues = "add_album_search_queue")
    public void receiveAddAlbumMessage(String id,Message message, Channel channel) {
        // 获取消息
        Long userId =Long.valueOf(id);
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        // 执行上架业务
        try {
            log.info("接收到专辑上架消息：{}", userId);
            itemService.addAlbumSearch(userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                if (messageProperties.getRedelivered()) {
                    log.error("专辑上架消息已重复处理失败，拒绝再次接收：{}", e.getMessage());
                    // 拒绝消息
                    channel.basicReject(deliveryTag, false);
                } else {
                    log.error("专辑上架消息即将再次返回队列处理：{}", e.getMessage());
                    // 将消息返回队列，并重新入队
                    channel.basicReject(deliveryTag,true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        }
    }

    /**
     * 接收专辑下架消息
     */

    @RabbitListener(queues = "delete_album_search_queue")
    public void receiveDeleteAlbumMessage(String id,Message message, Channel channel) {
        // 获取消息
        Long userId =Long.valueOf(id);
        // 获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        // 执行下架业务
        try {
            log.info("接收到专辑下架消息：{}", userId);
            itemService.removeAlbumSearch(userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                if (messageProperties.getRedelivered()) {
                    log.error("专辑下架消息已重复处理失败，拒绝再次接收：{}", e.getMessage());
                    // 拒绝消息
                    channel.basicReject(deliveryTag, false);
                } else {
                    log.error("专辑下架消息即将再次返回队列处理：{}", e.getMessage());
                    // 将消息返回队列，并重新入队
                    channel.basicReject(deliveryTag,true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        }
    }
}


